package be.dioubs.sportTrack;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import be.dioubs.sportTrack.adapter.DbAdapter;
import be.dioubs.sportTrack.adapter.TracksAdapter2;
import be.dioubs.sportTrack.common.Converter;
import be.dioubs.sportTrack.dialog.DialogTrackDetail;
import be.dioubs.sportTrack.dto.TrackDTO;

public class TabTracks extends ListActivity{
	public static final int ACTIVITY_CREATE = 0;
	public static final int ACTIVITY_EDIT = 1;
	
	public static final int INSERT_ID = Menu.FIRST;
	private static final int EDIT_ID = Menu.FIRST + 1;
    private static final int DELETE_ID = Menu.FIRST + 2;

    static final int DIALOG_TRACK_DETAIL = 0;
    static final int DIALOG_CONFIRM_DELETE_TRACK = 1;
    
	private DbAdapter mDbHelper;
	private Cursor mSportTracksCursor;
	private View mPreviousSelectedView;

	// Helps retrieve the current selected item
	private int mPosition = 0;
	private long mId;
	private long idToDelete = 0;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_content_tracks);
        mDbHelper = new DbAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
	}
	
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, EDIT_ID, 0, R.string.sport_track_menu_edit);
        menu.add(1, DELETE_ID, 0, R.string.sport_track_menu_delete);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	View actionView;
    	
        super.onListItemClick(l, v, position, id);
        
        mPosition = position;
        mId = id;
		
		// If a previous SubMenu was being showed, remove it
		if(mPreviousSelectedView != null)
		{
			LinearLayout previousEventListActions = (LinearLayout) mPreviousSelectedView.findViewById(R.id.eventListActions);
			previousEventListActions.setVisibility(View.GONE);
		}
		
		if(v != mPreviousSelectedView) {
			// Keeping a reference to the current selected item to easily remove the SubMenu later 
			mPreviousSelectedView = v;
			
			// Show the SubMenu of the current selected item
			LinearLayout eventListActions = (LinearLayout) v.findViewById(R.id.eventListActions);
	    	eventListActions.setVisibility(View.VISIBLE);
	    	
	    	// Listening for click event on SubMenu's elements
	    	// VIEW
	    	actionView = v.findViewById(R.id.eventListActionView);
	    	actionView.setOnTouchListener(onTouchListener);
	    	
	    	// EDIT
	    	actionView = v.findViewById(R.id.eventListActionEdit);
	    	actionView.setOnTouchListener(onTouchListener);

	    	// DUPLI
	    	actionView = v.findViewById(R.id.eventListActionDuplicate);
	    	actionView.setOnTouchListener(onTouchListener);	    	
	    	
	    	// DELETE
	    	actionView = v.findViewById(R.id.eventListActionDelete);
	    	actionView.setOnTouchListener(onTouchListener);  	

	    	// RATE
	    	actionView = v.findViewById(R.id.eventListActionRate);
	    	actionView.setOnTouchListener(onTouchListener);		
		}
		else
			mPreviousSelectedView = null;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()) {
        case DELETE_ID:
        	deleteTrack(info.id);
            return true;
        case EDIT_ID:
        	editTrack(info.position);
        	return true;
    	}
        
        return super.onContextItemSelected(item);
    }
	
    /* We override the default menu for this tab */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.clear();
        menu.add(0, INSERT_ID, 0, R.string.menu_insert);
        return result;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case INSERT_ID:
            createTrack();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void fillData() {
        // Get all of the tracks from the database and create the item list
    	mSportTracksCursor = mDbHelper.fetchAllTracks();
        startManagingCursor(mSportTracksCursor);

//        String[] from = new String[] {
//        		TrackDTO.KEY_TITLE,
//        		TrackDTO.KEY_DATE,
//        		TrackDTO.KEY_DISTANCE,
//        		TrackDTO.KEY_TIME
//        };
//        
//        int[] to = new int[] {
//        		R.id.title,
//        		R.id.date,
//        		R.id.distance,
//        		R.id.time
//        };
        
        // Now create an array adapter and set it to display using our row
//        TracksAdapter tracks =
//            new TracksAdapter(this, R.layout.tab_content_track, mSportTracksCursor, from, to);
//        
//        setListAdapter(tracks);
        
        List<TrackDTO> trackDtos = Converter.cursorToTrackDtos(mSportTracksCursor);
        TracksAdapter2 tracks2 =
            new TracksAdapter2(this, R.layout.tab_content_track, trackDtos);
        
        setListAdapter(tracks2);
    }

    private void createTrack() {
    	Intent i = new Intent(this, TrackEditor.class);
        startActivityForResult(i, ACTIVITY_CREATE);
    }    
    
    private void editTrack(int position) {
        Cursor c = mSportTracksCursor;
        c.moveToPosition(position);
        
        Intent i = new Intent(this, TrackEditor.class);
        Converter.cursorToIntentExtras(c, i);
        
        startActivityForResult(i, ACTIVITY_EDIT);
    }
    
    private void deleteTrack(long id) {
    	showDialog(DIALOG_CONFIRM_DELETE_TRACK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        if (intent != null) {
	        Bundle extras = intent.getExtras();
	        TrackDTO trackDTO = Converter.extrasToTrackDto(extras);
	        	
	        switch(requestCode) {
	            case ACTIVITY_CREATE:
	                mDbHelper.createTrack(trackDTO);
	                break;
	            case ACTIVITY_EDIT:
                    mDbHelper.updateTrack(trackDTO);
                    break;
	        }
	        
	        fillData();
        }
    }    
    
    /* WORK ON DIALOG CALLED BY showDialog(DIALOG_TRACK_DETAIL); */
    /* Not used for the moment */
    @Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
    	
    	switch (id) {
			case DIALOG_TRACK_DETAIL:
				DialogTrackDetail sportTrackDialog = new DialogTrackDetail(TabTracks.this,
						R.style.Dialog);
				
				return sportTrackDialog;
			case DIALOG_CONFIRM_DELETE_TRACK:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
				builder.setMessage(R.string.confirm_delete_track)
				       .setCancelable(false)
				       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				        	   mDbHelper.deleteTrack(idToDelete);
				               fillData();    	
				           }
				       })
				       .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				
				AlertDialog alert = builder.create();
				
				return alert;

			default:
				dialog = null;
				break;
		}
    	
    	return dialog;
    }

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
    	switch (id) {
			case DIALOG_TRACK_DETAIL:
		        Cursor c = mSportTracksCursor;
		        c.moveToPosition(mPosition);
		        
		        ((DialogTrackDetail)dialog).setTitle(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_TITLE)));
		        ((DialogTrackDetail)dialog).setDesccription(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_DESCRIPTION)));
		        ((DialogTrackDetail)dialog).setSport(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_SPORT)));
		        ((DialogTrackDetail)dialog).setDistanceNb(c.getLong(c.getColumnIndexOrThrow(TrackDTO.KEY_DISTANCE_NB)));
		        ((DialogTrackDetail)dialog).setDistanceUnit(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_DISTANCE_UNIT)));		        
		        ((DialogTrackDetail)dialog).setTime(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_TIME)));
		        ((DialogTrackDetail)dialog).setDate(c.getLong(c.getColumnIndexOrThrow(TrackDTO.KEY_DATE)));
		        ((DialogTrackDetail)dialog).setHeartRateMoy(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_HEART_RATE_MOY)));
		        ((DialogTrackDetail)dialog).setHeartRateMax(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_HEART_RATE_MAX)));
		        ((DialogTrackDetail)dialog).setFitnessLevel(c.getString(c.getColumnIndexOrThrow(TrackDTO.KEY_FITNESS_LEVEL)));
			default:
				dialog = null;
				break;
		}
	}
    /* END WORK ON DIALOG */

	//
	// LISTENERS
	//

    // Listener for Touch events
    private OnTouchListener onTouchListener = new OnTouchListener() {
    	public boolean onTouch(View view, MotionEvent motion) {
			switch(motion.getAction()) {
				case MotionEvent.ACTION_DOWN:
					touchDown(view);
					break;
				case MotionEvent.ACTION_UP:
					touchUp(view);
					break;
				case MotionEvent.ACTION_CANCEL:
				case MotionEvent.ACTION_OUTSIDE:
					view.setBackgroundDrawable(null);
					break;
			}

			return true;
    	}
    };    
    
    // When user touch the screen (before releasing his finger)
    private void touchDown(View view) {
    	Drawable clicked = getResources().getDrawable(R.drawable.action_clicked);
    	view.setBackgroundDrawable(clicked);
    }    
    
    // When user releases his finger from the screen
    private void touchUp(View view) {
    	view.setBackgroundDrawable(null);
    	
    	switch(view.getId()) {
    		case R.id.eventListActionView:
    			showDialog(DIALOG_TRACK_DETAIL);
    			break;
    		case R.id.eventListActionEdit:
    			editTrack(mPosition);
    			break;
    		case R.id.eventListActionDuplicate:
    			mDbHelper.deleteAllTrack();
    			fillData();
    			break;
    		case R.id.eventListActionDelete:
            	idToDelete = mId;
            	deleteTrack(mId);
    			break;
    		case R.id.eventListActionRate:
    	    	mDbHelper.createTestTracks();
    	    	fillData();
    			break;
    	}
    }
}